package com.adtech.adms.commons.web.intercepter;

import java.util.List;
import java.util.Map;

import com.adtech.adms.SessionKey;
import com.adtech.adms.commons.tree.TreeNode;
import com.adtech.adms.commons.util.TreeUtil;
import com.adtech.adms.commons.util.TreeUtil.OnGetNodeListener;
import com.adtech.adms.system.pojo.Feature;
import com.adtech.adms.system.pojo.User;
import com.adtech.core.exception.ErrorCode;
import com.adtech.core.exception.ServiceException;
import com.opensymphony.xwork2.ActionInvocation;


/**
 * @author apple
 *
 */
public class AclInterceptor extends BaseInterceptor {

	private static final long serialVersionUID = -3155760331125228568L;

	@Override
	public String intercept(final ActionInvocation invocation) throws Exception {

		Map<String, Object> session = super.getSession(invocation);
		if (session != null && session.get(SessionKey.SESSION_KEY_USER) != null) {
			User user = (User) session.get(SessionKey.SESSION_KEY_USER);
			List<TreeNode<Feature>> tree = user.getFeaturesTree();

			final String nameSpace = invocation.getProxy().getNamespace();
			final String actionName = super.getActionName(invocation);

			for (TreeNode<Feature> node : tree) {
				TreeNode<Feature> n = TreeUtil.iteratorNodes(node, new OnGetNodeListener<Feature>() {
					public boolean onGetNode(TreeNode<Feature> node) {
						String url = nameSpace +"/"+actionName;
						return url.equals(node.getUrl()) || (url+".action").equals(node.getUrl());

					}
				});

				if (n != null) {
					return invocation.invoke();
				}
			}
		}

		throw new ServiceException(ErrorCode.PRIVILEGE_ERROR);
	}
}
